// 请求模块

// 导入axios
import axios from 'axios'
import store from '@/store/index.js'
import JSONBig from 'json-bigint'
import { Toast } from 'vant';
import router from "../router";
//解密加密
import {
  Sm4Dncrypt,
  Sm4encrypt
} from '@/utils/encryption.js'

const request = axios.create({
  // 接口的基准路径
  baseURL: process.env.VUE_APP_TYPE === 'APP' ? process.env.VUE_APP_BASE_API : '',
  // 自定义后端返回的原始数据
  // data:后端返回的原始数据 就是json格式的字符串
  TransformResponse: [
    function (data) {
      try {
        return JSONBig.parse(data)
      } catch (err) {
        return data
      }
    }
  ]
})

// 请求拦截器
// Add a request interceptor
request.interceptors.request.use(
  function (config) {
    if (config.url == '/ocr') {
      config.baseURL = process.env.VUE_APP_OCR_API
    }
    // app打包无需代理
    if (process.env.VUE_APP_TYPE === 'APP' && config.url.length > 0 && config.url.indexOf('/api') != -1) {
      config.url = config.url.replace('/api', '')
    }
    // 控制解密报错
    let token = ""
    if (sessionStorage.getItem("token")) {
      token = Sm4Dncrypt(sessionStorage.getItem("token"))
    }
    if (token) {
      //让每个请求头部携带token
      config.headers["token"] = token;
    }
    // config 里面有一个属性：headers
    const { user } = store.state
    if (user && user.token) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 登录接口，获取token
    if ((response.config.url == "/api/user/login-v1" || response.config.url == "/user/login-v1") && response.data.succeed) {
      let token = response.data.data.token
      sessionStorage.setItem("token", Sm4encrypt(token));
    }
    if (response.data.succeed) {
      return response.data;
    } else {
      const res = response.data
      if (response.config.url == '/ocr') {
        // 拦截公司ocr接口
        return response.data;
      }
      if (res.status == "401") {
        Toast.fail(res.msg);
        return redirectLogin();
      }
      if (res.status === 1001 || res.status === 1002 || res.status === 1003 || res.status === 1004) {
        return response.data;
      }
      if (res.status !== 200) {
        if (response.config.customMsg) {
          return Promise.reject(res);
        } else {
          if (res.msg == 'token已过期') {
            redirectLogin()
          }
          Toast.fail(res.msg);
          return response.data;;
        }

      } else {
        Toast.fail(res.msg);
        return res;
      }
    }
  },
  error => {
    console.log(error);
    if (!error.response) {
      // 断网了  
      Toast.fail('请检查网络');
      // Message({
      //   message: "网络已断开！",
      //   type: "error",
      //   duration: 5 * 1000
      // });
      return false
    }

    try {
      Toast.fail('系统错误');
      // Message({
      //   message: error || "Error",
      //   type: "error",
      //   duration: 5 * 1000
      // });
      return error.response
    } catch (e) {
      sessionStorage.removeItem("token");
      location.href = "/";
    }
  }
);

function redirectLogin() {
  router.replace({ path: "/" });
}

export default request